package test;

public class BytesUtils {

    public static void main(String args[]) {

        String b = "12345";
        byte[] bytes = b.getBytes();
        FileWriteContext f = new FileWriteContext();
        f.append(bytes);
        System.out.println(new String(f.getBuffer()));
        b = "56789";
        bytes = b.getBytes();
        f.append(bytes);
        b = "abcdf";
        bytes = b.getBytes();
        f.append(bytes);
        byte[] bb = f.flushBuffer();
        System.out.println(new String(bb)+" "+bb.length);

    }

    public static class FileWriteContext {
        private byte []  buffer;

        public byte[] getBuffer(){
            return this.buffer;
        }

        public byte[] flushBuffer(){
            byte [] returnBytes = buffer;
            buffer = null;
            return returnBytes;
        }

        public void append(byte[] bytes){
            int destPoc = 0;
            if(buffer == null){
                buffer = new byte[bytes.length];
            }else{
                destPoc = buffer.length;
                byte [] lastBuffer = buffer;
                buffer = new byte[lastBuffer.length+bytes.length];
                System.arraycopy(lastBuffer,0,buffer,0,lastBuffer.length);
            }
            System.arraycopy(bytes,0,buffer,destPoc,bytes.length);
        }

    }
}
